package com.zzhrtech.wgzx_cityzen.ui.me;

import android.app.Dialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Map;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.GsonRequest;
//import com.hyphenate.EMCallBack;
//import com.hyphenate.chat.EMClient;
import com.zzhrtech.WgzxApplication;
import com.zzhrtech.wgzx_cityzen.BaseActivity;
import com.zzhrtech.wgzx_cityzen.Constans;
import com.zzhrtech.wgzx_cityzen.MainActivity;
import com.zzhrtech.wgzx_cityzen.R;
import com.zzhrtech.wgzx_cityzen.beans.me.LoginBean;
import com.zzhrtech.wgzx_cityzen.view.CustomProgress;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends BaseActivity {
    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    // UI references.
    private EditText mEmailView;
    private EditText mPasswordView;

    private Dialog proDialog;
    private TextView tv_regeist;
    private TextView tv_forget;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        toolbar.setNavigationIcon(R.mipmap.ic_close);

        proDialog = CustomProgress.show(this,true,null);

        // Set up the login form.
        mEmailView = (EditText) findViewById(R.id.email);

        mPasswordView = (EditText) findViewById(R.id.password);

        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        tv_regeist = (TextView) findViewById(R.id.tv_regeist);
        tv_regeist.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
                startActivity(intent);
            }
        });

        tv_forget = (TextView) findViewById(R.id.tv_forget);
        tv_forget.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this,ForgetPwdActivity.class);
                startActivity(intent);
            }
        });
    }




    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mPasswordView.setError("密码太短");
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError("帐号不能为空");
            focusView = mEmailView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.

            proDialog.show();
            httpLogin(email,password);
        }
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 4;
    }

    private void httpLogin(String uname,String pwd){
        Map<String,String> params = new HashMap<String, String>();
        params.put("username",uname);
        params.put("password",pwd);

        GsonRequest<LoginBean> gsonRequest = new GsonRequest<LoginBean>(com.android.volley.Request.Method.POST, Constans.HTTP_LOGIN, LoginBean.class, params, new com.android.volley.Response.Listener<LoginBean>() {
            @Override
            public void onResponse(LoginBean response) {
                if (response.isSuccess()){
                    Message message = new Message();
                    message.what = 0;
                    message.obj = response.getData();
                    mHandler.sendMessage(message);
                }else {
                    proDialog.dismiss();
                    showToast(response.getMsg());
                }
            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                proDialog.dismiss();

                showToast("登录失败");
                Log.d("result=====",error + "");
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }


    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            if (msg.what == 0) {

                proDialog.dismiss();
                LoginBean.Data data = (LoginBean.Data) msg.obj;
                getCache().put(keyUid, data.getId());
                getCache().put(keyUsername, data.getUsername());
                getCache().put(keyNickname, data.getNickname());
                getCache().put(keyAccount,data.getAccount());
                if (data.getHead() != null)
                getCache().put(keyHead, data.getViewhead());
                if (data.getViewhead() != null)
                getCache().put(keyViewHead,data.getViewhead());

                Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                startActivity(intent);
                finish();
            }

            return false;
        }
    });

}

